package com.jitu.ocr.component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.util.Base64Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Configuration
@Slf4j
public class OCR {

    private static final int TIME_OUT = 30000;

    @Bean
    public void ocr() {
        String m = null;

        CloseableHttpClient client = null;
        try {
            client = HttpClients.createDefault();
            String url = "http://192.168.4.96:5000/ocr/";
            HttpPost httpPost = new HttpPost(url);

            // 配置请求的超时设置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(TIME_OUT)
                    .setConnectTimeout(TIME_OUT)
                    .setSocketTimeout(TIME_OUT).build();
            httpPost.setConfig(requestConfig);

            httpPost.setHeader("charset", "UTF-8");
            httpPost.setHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE);

            // 读取图片
            File file = new File("src/main/resources/img/img_3.png");
            FileInputStream is = new FileInputStream(file);
            byte[] fileBytes = new byte[(int) file.length()];
            is.read(fileBytes);
            is.close();
            String imgBase64Str = Base64Utils.encodeToString(fileBytes);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("imgbase64", imgBase64Str);

            StringEntity paramEntity = new StringEntity(jsonObject.toString(), StandardCharsets.UTF_8);
            paramEntity.setContentEncoding(StandardCharsets.UTF_8.toString());
            httpPost.setEntity(paramEntity);

            // 响应内容
            CloseableHttpResponse response = client.execute(httpPost);

            // 成功响应，读取返回内容
            HttpEntity entity = response.getEntity();
            // 转换entity为字符串
            m = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            parse(JSONObject.parseObject(m));

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 营业执照新版（横版）、老版（竖版）
    private void parse(JSONObject jsonObject) {
        List<JSONArray> boxes = jsonObject.getJSONArray("boxes").toJavaList(JSONArray.class);
        List<String> strings = jsonObject.getJSONArray("strings").toJavaList(String.class);
//        for ( JSONArray jsonArray : boxes) {
//            List<double[]> points = jsonArray.toJavaList(double[].class);
//            System.out.println(jsonArray.toString());
//        }

        for (int i = 0; i < boxes.size(); i++) {
            List<double[]> points = boxes.get(i).toJavaList(double[].class);
            System.out.println(boxes.get(i).toString() + " ：" + strings.get(i));
        }

        String stringsAll = String.join("", strings);
        System.out.println(strings.toString());
        System.out.println(stringsAll);
        String timecost = jsonObject.getString("timecost");
        System.out.println(timecost);

    }

}
